const storageType = window.sessionStorage
const PREFIX = 'PORTFOLIO-'

class Storage {
  get(key) {
    key = PREFIX + key
    const keyName = storageType.getItem(key)
    if (keyName === null) {
      return null
    }

    const valArr = keyName.split('|')
    const dataType = valArr[valArr.length - 1]
    valArr.splice(valArr.length - 1, 1)
    let val = valArr.join('')

    if (dataType === 'Number') {
      val = parseInt(val)
    } else if (dataType === 'Boolean') {
      val = val === 'true'
    } else if (dataType === 'Array' || dataType === 'Object' || dataType === 'Null') {
      val = JSON.parse(val)
    }
    return val
  }

  set(obj) {
    function cacheItem(key, val) {
      key = PREFIX + key
      const valType = typeof val
      let valConstructor = ''
      if (val !== null) {
        valConstructor = val.constructor
      }
      if (valType === 'string' || valType === 'number' || valType === 'boolean') {
        if (valConstructor === String) {
          val = `${val}|String`
        } else if (valConstructor === Number) {
          val = `${val}|Number`
        } else if (valConstructor === Boolean) {
          val = `${val}|Boolean`
        }
        storageType.setItem(key, val)
      } else if (valType === 'object') {
        if (val === null) {
          val = `${JSON.stringify(val)}|Null`
        } else if (valConstructor === Array) {
          val = `${JSON.stringify(val)}|Array`
        } else if (valConstructor === Object) {
          val = `${JSON.stringify(val)}|Object`
        }
        storageType.setItem(key, val)
      }
    }

    for (const key in obj) {
      cacheItem(key, obj[key])
    }
  }

  remove(key) {
    key = PREFIX + key
    storageType.removeItem(key)
  }

  clear() {
    for (const key in storageType) {
      if (key.includes(PREFIX)) {
        storageType.removeItem(key)
      }
    }
  }
}

const storage = new Storage()
export default storage
